import axios from "axios";
const cookieparser = process.server ? require("cookieparser") : undefined;

const baseUrl = "http://realworld.api.fed.lagounews.com";

export const request = axios.create({
  baseURL: baseUrl,
  timeout: 1500,
  retry: 3,
  retryDelay: 1000,
});

export default ({ store, req }) => {
  let { user } = store.state;

  if (!user) {
    if (req && req.header && req.headers.cookie) {
      const parsed = cookieparser.parse(req.headers.cookie);
      try {
        user = JSON.parse(parsed.user);
      } catch (err) {
        user = null;
      }
    }
  }
  if (user && user.token) {
    request.interceptors.request.use(
      function(config) {
        config.headers.Authorization = `Token ${user.token}`;
        return config;
      },
      function(err) {
        return Promise.rejecte(err);
      }
    );
  }

  request.interceptors.response.use(
    function(response) {
      return response;
    },
    function axiosRetryInterceptor(err) {
      const config = err.config;

      if (!config || !config.retry) return Promise.reject(err);

      if (
        err.code == "ECONNABORTED" &&
        err.message.indexOf("timeout") != -1 &&
        config._retry
      ) {
        config.__retryCount = config.__retryCount || 0;

        if (config.__retryCount >= config.retry) {
          return Promise.reject(err);
        }

        config.__retryCount += 1;

        var backoff = new Promise(function(resolve) {
          setTimeout(function() {
            resolve();
          }, config.retryDelay || 1);
        });

        return backoff.then(function() {
          return axios(config);
        });
      }
      return Promise.reject(err);
    }
  );
};
